<?php
/**
 * Created by PhpStorm.
 * User: nightelf
 * Date: 2020/2/4
 * Time: 20:54
 */

namespace App\Http\Controllers\Setting;


use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Model\SettingModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class SettingController extends Controller
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function getRate(Request $request){
        $rules = [
            'projectId' => 'required|integer',
        ];
        $message = [
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
        ];
        $param = $request->only(['projectId', 'month']);
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $settingModel = new SettingModel();
            $this->data = $settingModel->get('saleRate',$param['projectId']);
        } else {
            throw new ApiException($validator->errors()->first(), 210101);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function setRate(Request $request){
        $rules = [
            'projectId' => 'required|integer',
            'rate' => 'required|numeric|min:0',
        ];
        $message = [
            'projectId.required' => '获取项目参数错误',
            'projectId.integer' => '项目参数类型错误',
            'rate.required' => '请填写溢价率',
            'rate.numeric' => '溢价率类型错误',
            'rate.min' => '溢价率不能小于0',
        ];
        $input = $request->only(['projectId', 'rate']);
        $validator = Validator::make($input, $rules, $message);
        if ($validator->passes()) {
            $settingModel = new SettingModel();
            $settingModel->set('saleRate',$input['rate']/100,$input['projectId']);
        } else {
            throw new ApiException($validator->errors()->first(), 210101);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }
}